/**
 * Created by wangxinxin on 2019/2/18.
 */
import React, { useState, useEffect, useRef }  from 'react';
import { Form, Input, Button, Row, Col } from 'antd';
import _ from 'lodash';

function usePrevious(value) {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
}

function Room(props) {
  const [ws, setWs] = useState(null);
  const [users, setUsers] = useState([]);
  const [messages, setMessages] = useState([]);
  const prevUsers = usePrevious(users) || [];
  const prevMessages = usePrevious(messages) || [];
  useEffect(() => {
    const ws = new WebSocket('ws://127.0.0.1:3001/ws/chat');
    setWs(ws);
    ws.onmessage = (e) => {
      const data = e.data;
      console.log(data);
      const msg = JSON.parse(data);
      if(msg.type == 'list'){
        setUsers(msg.data);
      }else if(msg.type == 'join'){
        prevUsers.push(msg.user);
        prevMessages.push(msg);
        setUsers(prevUsers);
        setMessages([...prevMessages]);
      }else if(msg.type == 'left'){
        // _.filter的反向方法
        const currentUsers = _.reject(prevUsers, {id: msg.user.id});
        prevMessages.push(msg);
        setUsers(currentUsers);
        setMessages([...prevMessages]);
      }else if(msg.type == 'chat'){
        prevMessages.push(msg);
        setMessages([...prevMessages]);
      }
    }
    ws.onclose = function (evt) {
      console.log('[closed] ' + evt.code);
    }
    ws.onerror = function (code, msg) {
      console.log('[ERROR] ' + code + ': ' + msg);
    };
  },[]);
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        ws.send(values.message);
        props.form.resetFields();
      }
    })
  }
  const { getFieldDecorator } = props.form;
  return(
    <Row>
      <Col span={18}>
        <div id="message-list">
          <h3>message-list</h3>
          {messages.map(msg=>(
            <div key={msg.id}>
              { (msg.type=="join" || msg.type=="left") && <h4>{msg.data}</h4> }
              {
                msg.type=="chat" &&
                <React.Fragment>
                  <h4>{msg.user.name}:</h4>
                  <span>{msg.data}</span>
                </React.Fragment>
              }
            </div>
          ))}
        </div>
        <hr />
        <div id="chat">
          <Form layout="inline" onSubmit={handleSubmit} className="login-form">
            <Form.Item>
              {getFieldDecorator('message', {
                rules: [{ required: true, message: 'Please input message!' }],
              })(
                <Input placeholder="message" />
              )}
            </Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              Go!
            </Button>
          </Form>
        </div>
      </Col>
      <Col span={6}>
        <div id="user-list">
          <h3>user-list</h3>
          {users.map(item => (
            <h4 key={item.id}>{item.name} ({item.id})</h4>
          ))}
        </div>
      </Col>
    </Row>
  );
}

export default Form.create()(Room);

